<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>系统登录</h2>
      </div>

      <el-form ref="loginForm" :model="ruleForm" :rules="rules" class="login-form">
        <el-form-item prop="account">
          <el-input
            v-model="ruleForm.account"
            placeholder="请输入用户名"
            prefix-icon="User"
            clearable
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="ruleForm.password"
            type="password"
            placeholder="请输入密码"
            prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item prop="checkCode" v-if="showCaptcha">
          <div class="captcha-container">
            <el-input
              v-model="ruleForm.checkCode"
              placeholder="请输入验证码"
              prefix-icon="Key"
              @keyup.enter="handleLogin"
            />
            <img :src="captchaUrl" class="captcha-img" @click="refreshCaptcha" />
          </div>
        </el-form-item>

        <el-form-item>
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" class="login-btn" :loading="loading" @click="handleLogin()">
            登 录
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import request from '@/util/request'
import qs from 'qs'
import {
  User as UserIcon,
  Lock as LockIcon,
  Key as KeyIcon,
} from '@element-plus/icons-vue'
import axios, { Axios } from 'axios'

interface RuleForm {
  account: string
  password: string
  checkCode: string
}

const router = useRouter()
const loginForm = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  account: '',
  password: '',
  checkCode: '',
})



const rules = reactive<FormRules<RuleForm>>({
  account: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' },
  ],
  checkCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 4, max: 4, message: '验证码长度为 4 个字符', trigger: 'blur' },
  ],
})

const rememberMe = ref(false)
const loading = ref(false)
const showCaptcha = ref(true)
const captchaUrl = ref('')

async function refreshCaptcha() {
  try {
    const resp = await request.get('/per/user/getCaptcha', {
      responseType: 'arraybuffer',
    })
    const base64 = btoa(
      new Uint8Array(resp.data).reduce((s, byte) => s + String.fromCharCode(byte), '')
    )
    captchaUrl.value = `data:image/jpeg;base64,${base64}`
  } catch {
    ElMessage.error('获取验证码失败')
  }
}

async function handleLogin() {
  console.log("123");
  if (!loginForm.value) return
  loginForm.value.validate(async (valid, _) => {
    if (!valid) return

    loading.value = true
    try {
      const payload = qs.stringify({
        account: ruleForm.account,
        password: ruleForm.password,
        checkCode: ruleForm.checkCode,
      })
      console.log(ruleForm.account+","+ruleForm.password);
      const res = await request.post(
        '/per/user/login',
        payload,
        { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }
      )
      console.log("123123")
      if (res.data.code === '200') {
        const d = res.data.data
        const user = d.user
        sessionStorage.setItem("user", JSON.stringify({ user }))
        sessionStorage.setItem('token', d.token)
        sessionStorage.setItem('refreshToken', d.refreshToken)
        sessionStorage.setItem('menuTree', JSON.stringify(d.menuTree))
        sessionStorage.setItem('permissions', JSON.stringify(d.permissions))
        ElMessage.success('登录成功')

        if (rememberMe.value) {
          localStorage.setItem(
            'rememberedUser',
            JSON.stringify({ account: ruleForm.account })
          )
        } else {
          localStorage.removeItem('rememberedUser')
        }
        router.push('/home/index')
      } else if (res.data.code === '303') {
        ElMessage.error('验证码错误')
        ruleForm.checkCode = ''
        await refreshCaptcha()
      } else {
        ElMessage.error('用户名或密码错误')
      }
    } catch {
      ElMessage.error('登录失败，请重试')
    } finally {
      loading.value = false
    }
  })
}

onMounted(() => {
  if (showCaptcha.value) {
    refreshCaptcha()
  }
  const remembered = localStorage.getItem('rememberedUser')
  if (remembered) {
    ruleForm.account = JSON.parse(remembered).account
    rememberMe.value = true
  }
})
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #1a2980 0%, #26d0ce 100%);
}
.login-box {
  width: 400px;
  padding: 40px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 10px;
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);
}
.login-header {
  text-align: center;
  margin-bottom: 30px;
}
.login-header h2 {
  color: #333;
}
.login-form {
  margin-top: 20px;
}
.captcha-container {
  display: flex;
  align-items: center;
}
.captcha-img {
  width: 100px;
  height: 40px;
  margin-left: 10px;
  cursor: pointer;
  border: 1px solid #ddd;
  border-radius: 4px;
}
.login-btn {
  width: 100%;
  height: 45px;
  font-size: 16px;
}
</style>
